﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using JSH.ITDiplom.OOPC01.PersonalIdentityNumber.BusinessLayer;
using JSH.ITDiplom.OOPC01.PersonalIdentityNumber.BusinessLayer.da;
using JSH.ITDiplom.OOPC01.PersonalIdentityNumber.BusinessLayer.se;
using JSH.ITDiplom.OOPC01.PersonalIdentityNumber.DataLayer;

namespace JSH.ITDiplom.OOPC01.PersonalIdentityNumber.UILayer.WFA
{
    /// <summary>
    /// Main form
    /// </summary>
    public partial class FormMain : Form
    {
        private readonly ResourceManager resourceManager;
        private HtmlForm htmlHelpForm;

        /// <summary>
        /// Initialize main form.
        /// </summary>
        public FormMain()
        {
            InitializeComponent();
            dateTimePickerDa.MaxDate = DanishPersonalIdentityNumber.MAX_DATE;
            dateTimePickerDa.MinDate = DanishPersonalIdentityNumber.MIN_DATE;
            int minYear = DateTime.Now.Year - 199;
            dateTimePickerSe.MinDate = new DateTime(minYear, 1, 1);
            resourceManager = 
                new ResourceManager(
                    "JSH.ITDiplom.OOPC01.PersonalIdentityNumber.UILayer.WFA.Resource",
                    typeof(FormMain).Assembly);
            AcceptButton = buttonDaCheck;
            textBoxDaCPRnummer.Focus();
            buttonDaSave.Enabled = false;
            buttonSeSave.Enabled = false;
        }

        /// <summary>
        /// Close main form.
        /// </summary>
        private void buttonClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Validate Danish personal identity number.
        /// </summary>
        private void buttonCheckDa_Click(object sender, EventArgs e)
        {
            BusinessLayer.PersonalIdentityNumber pin = 
                new DanishPersonalIdentityNumber(textBoxDaCPRnummer.Text);
            IList<string> errors;
            bool valid = pin.Validate(out errors);
            webBrowserDaResult.DocumentText = MakeResult(valid, pin, errors);
        }

        /// <summary>
        /// Validate Swedish personal identity number.
        /// </summary>
        private void buttonCheckSe_Click(object sender, EventArgs e)
        {
            BusinessLayer.PersonalIdentityNumber pin = 
                new SwedishPersonalIdentityNumber(textBoxSePersonalNummer.Text);
            IList<string> errors;
            bool valid = pin.Validate(out errors);
            webBrowserSeResult.DocumentText = MakeResult(valid, pin, errors);
        }

        /// <summary>
        /// Create personal identity number validation html output.
        /// </summary>
        /// <param name="valid">True if it is a valid number.</param>
        /// <param name="pin">Personal identity number</param>
        /// <param name="errors">A List of errors.</param>
        /// <returns>Html output</returns>
        private string MakeResult(bool valid,
            BusinessLayer.PersonalIdentityNumber pin,
            IEnumerable<string> errors)
        {
            const string fontStyle =
                "style=\"font-family:Sans Serif\" style=\"font-size:80%\"";
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<p " + fontStyle + ">");
            if (valid)
            {
                sb.AppendLine("Ok!</br>");
                if (pin.BirthDay != null)
                {
                    //Casting from DateTime? to DateTime.
                    DateTime dt = (DateTime)pin.BirthDay;  
                    sb.AppendLine("Fødselsdag: "
                        + dt.ToShortDateString()
                        + "</br>");
                }
                sb.AppendLine("Køn: "
                    + resourceManager.GetString(pin.Gender.ToString())
                    + "</br>");
            }
            else
            {
                sb.AppendLine("Fejl:");
                foreach (string s in errors)
                {
                    string error = resourceManager.GetString(s.Replace('.', '_'));
                    sb.AppendLine("<li " + fontStyle + ">" + error + "</li>");
                }
            }
            sb.AppendLine("</p>");
            return sb.ToString();            
        }

        private void FormMain_Shown(object sender, EventArgs e)
        {
            textBoxDaCPRnummer.Focus();
        }

        /// <summary>
        /// Set Accept button when a new tab is selected.
        /// </summary>
        private void tabControl_Selected(object sender, TabControlEventArgs e)
        {
            if (e.TabPage == tabPageDaValidation)
            {
                AcceptButton = buttonDaCheck;                
            }
            else if (e.TabPage == tabPageSeValidation)
            {
                AcceptButton = buttonSeCheck;
            }
            else if (e.TabPage == tabPageDaGeneration)
            {
                AcceptButton = buttonDaGenerate;
            }
            else if (e.TabPage == tabPageSeGeneration)
            {
                AcceptButton = buttonSeGenerate;
            }
        }

        /// <summary>
        /// Show help dialog.
        /// </summary>
        private void buttonHelp_Click(object sender, EventArgs e)
        {
            if (htmlHelpForm == null)
            {
                htmlHelpForm = new HtmlForm {Text = "Hjælp", 
                    Size = new Size(800, 520)};
                htmlHelpForm.Closed += htmlHelpForm_Closed;
                if (resourceManager != null)
                {
                    string html = (string)resourceManager.GetObject("help");
                    
                    htmlHelpForm.SetHtmlText(html);
                }
                htmlHelpForm.Show();
            }
            else
            {
                htmlHelpForm.BringToFront();
            }
        }

        /// <summary>
        /// Event called when the help dialog is closed.
        /// </summary>
        void htmlHelpForm_Closed(object sender, EventArgs e)
        {
            htmlHelpForm = null;
        }

        /// <summary>
        /// Show about dialog.
        /// </summary>
        private void buttonAbout_Click(object sender, EventArgs e)
        {
            HtmlForm htmlAboutForm = new HtmlForm { Text = "Om" };
            string html = (string) resourceManager.GetObject("about");
            htmlAboutForm.SetHtmlText(html);
            htmlAboutForm.ShowDialog();
            htmlAboutForm.Close();
        }

        /// <summary>
        /// Generate Danish personal identity numbers.
        /// </summary>
        private void buttonDaGenerate_Click(object sender, EventArgs e)
        {
            Gender gender = Gender.Female;
            if (radioButtonDaMale.Checked)
            {
                gender = Gender.Male;
            }
            IList<string> numbers = DanishPersonalIdentityNumber.Generate(
                dateTimePickerDa.Value,
                gender);
            StringBuilder sb = new StringBuilder();
            foreach (string s in numbers)
            {
                sb.AppendLine(s);
            }
            richTextBoxDaResult.Text = sb.ToString();
            labelDaCount.Text = "Antal: " + numbers.Count;
            buttonDaSave.Enabled = true;
        }

        /// <summary>
        /// Generate Swedish personal identity numbers.
        /// </summary>
        private void buttonSeGenerate_Click(object sender, EventArgs e)
        {
            Gender gender = Gender.Female;
            if (radioButtonSeMale.Checked)
            {
                gender = Gender.Male;
            }
            IList<string> numbers = SwedishPersonalIdentityNumber.Generate(
                dateTimePickerSe.Value,
                gender);
            StringBuilder sb = new StringBuilder();
            foreach (string s in numbers)
            {
                sb.AppendLine(s);
            }
            richTextBoxSeResult.Text = sb.ToString();
            labelSeCount.Text = "Antal: " + numbers.Count;
            buttonSeSave.Enabled = true;
        }

        /// <summary>
        /// Save Danish personal identity numbers.
        /// </summary>
        private void buttonDaSave_Click(object sender, EventArgs e)
        {
            Save(richTextBoxDaResult.Text);
        }

        /// <summary>
        /// Save Swedish personal identity numbers.
        /// </summary>
        private void buttonSeSave_Click(object sender, EventArgs e)
        {
            Save(richTextBoxSeResult.Text);
        }

        /// <summary>
        /// Shows a save file dialog and save data to the selected file.
        /// </summary>
        /// <param name="data">data to save to file</param>
        private static void Save(string data)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                DefaultExt = "txt",
                Filter = "Text file (*.txt)|*.txt|All files (*.*)|*.*",
                AddExtension = true,
                RestoreDirectory = true,
                InitialDirectory = @"C:/"
            };
            // Show the dialog and process the result
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                SaveFile.save(saveFileDialog.FileName, data);
                MessageBox.Show("Personnumre er nu gemt i filen: "
                    + saveFileDialog.FileName,
                    "Fil gemt", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}